# -*- coding: utf-8 -*-
from selenium import webdriver
import time, os

from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
DesiredCapabilities.INTERNETEXPLORER["ignoreProtectedModeSettings"] = True
  
def capture(url, pix_w=1200, pix_h=1500, output_dir=".", save_fn="capture"):
  chromedriver = "D:\Sycee\ci_jenkins\monitor_rc_loadtime\webdrivers\chromedriver.exe"
  iedriver = "D:\Sycee\ci_jenkins\monitor_rc_loadtime\webdrivers\IEDriverServer.exe"
  ie32driver = "D:\Sycee\ci_jenkins\monitor_rc_loadtime\webdrivers\IEDriverServer_x32.exe"
  firefoxdriver = "D:\Sycee\ci_jenkins\monitor_rc_loadtime\webdrivers\geckodriver.exe" 
  os.environ["webdriver.chrome.driver"] = chromedriver          #chrome不能截全图, 在screenshot2中分截几个图,然后合并
  os.environ["webdriver.ie.driver"] = ie32driver    #iedriver   #ie可以全屏截图,但是jenkins中报错
  os.environ["webdriver.firefox.driver"] = firefoxdriver        #firefox可以截长图,但是要定义高度
  
  #browser = webdriver.Chrome(chromedriver) # Get local session of chrome
  #browser = webdriver.Ie(iedriver) # Get local session of ie
  browser = webdriver.Firefox(executable_path=firefoxdriver)
  browser.set_window_size(pix_w, pix_h)
  browser.get(url) # Load page
  #find_element_by_name、find_element_by_id
  elem_pwd = browser.find_element_by_xpath('//input[@type="password"]')
  if elem_pwd:
      elem_pwd.send_keys('Aa123456')
      commit = browser.find_element_by_xpath('//input[@type="submit"]')
      commit.click()
      time.sleep(3)

  browser.execute_script("""
    (function () {
      var y = 0;
      var step = 100;
      window.scroll(0, 0);
  
      function f() {
        if (y < document.body.scrollHeight) {
          y += step;
          window.scroll(0, y);
          setTimeout(f, 50);
        } else {
          window.scroll(0, 0);
          document.title += "scroll-done";
        }
      }
  
      setTimeout(f, 1000*20);
    })();
  """)
  
  for i in xrange(30):
    if "scroll-done" in browser.title:
      break
    time.sleep(1)
    
  save_path = '%s/%s.png' % (output_dir, save_fn) 
  browser.save_screenshot(save_path)
  browser.close()
  
  
if __name__ == "__main__":
  
  #capture("https://app.klipfolio.com/published/dacd765df0130f4a5b3d894621db04b9/jobsdb-rc-web--hk")
  capture("https://app.klipfolio.com/published/3686896229564e74c3141662ea7945fc/jobsdb-rc-web--id")